import React, { useContext } from 'react';
import { useState, useEffect } from 'react';
import PodcastCard from './PodcastCard';
import api from './api/api';
import DataContext from './context/DataContext';

const AllPodcasts = () => {

  const { keyword, setKeyword } = useContext(DataContext);
  const [podcasts, setPodcasts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchAllPodcasts = async () => {
      try {
        const baseUrl = api.getUri();
        const limit = 100;
        const response = await api.get(`/podcasts?limit=${limit}`);
        let returnedPodcasts = response.data;
        returnedPodcasts = returnedPodcasts.map((podcast) => {
          podcast.coverUrl = `${baseUrl}/podcasts/${podcast.id}/cover`;
          return podcast;
        });
        setPodcasts(returnedPodcasts);
        setIsLoading(false);
      }
      catch (err) {
        console.log(`Error:${err.message}`);
      }
    };
    fetchAllPodcasts();
  }, []);
  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container">
        <h1 className='mt-2 mb-5'>全部播客</h1>
        {!isLoading &&
          <div className="row justify-content-start">
            {podcasts
              .filter(
                (podcast) => {
                  return podcast.title.toLowerCase().includes(keyword.toLowerCase());
                }
              )
              .map((podcast) => (
                <PodcastCard key={podcast.id} id={podcast.id} title={podcast.title} coverUrl={podcast.coverUrl} />
              ))}
          </div>
        }
        <div className="mb-3"></div>
      </div>
    </div>
  );
};

export default AllPodcasts;
